import Util from "../../utils/util";
import Status from "../../utils/status";
import {printerInitData, shopPrinter} from "../../api/shop";

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fields: {
      printer_id: {title: "打印机", type: "select", range_key: "title", required: true},
      stall_id: {title: "档口", type: "checkbox", placeholder: "全部", range_key: "title"},
    },
    btnActive: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;
    this.setData({...options})
    this.setData({
      navH: app.globalData.navHeight,
      barHeight: app.globalData.barHeight || 20,
      printerTypeTitle: "打印" + Status.printerType(this.data.printer_type)
    });

    if (this.data.printer_type != 'label') {
      let fields = this.data.fields;
      delete fields['stall_id'];
      this.setData({fields: fields})
    }

    if (Util.isEmpty(this.data.printer_type)) {
      let tData = {
        tab: getCurrentPages().length > 1 ? 3 : 5
      };
      if (getCurrentPages().length == 1) {
        tData.url = "/pages/console/index"
      }
      return Util.Tips({title: "请选择打印类型"}, tData)
    }

    let shopAdmin = wx.getStorageSync("SHOP_ADMIN");
    if (wx.getStorageSync("shop_accessToken")) {
      shopAdmin = Util.isEmpty(shopAdmin) ? null : JSON.parse(shopAdmin);
      if (Util.isEmpty(shopAdmin)) {
        return Util.Tips({title: "请先登录"}, {tab: 5, url: "../console/login"});
      }
      this.setData({
        shopAdmin: shopAdmin,
      })
      that.initTop();

      let filter = {};
      if (!Util.isEmpty(this.data.id)) {
        filter.ids = this.data.id;
      }
      if (!Util.isEmpty(this.data.current_date)) {
        filter.current_date = this.data.current_date;
      }
      if (!Util.isEmpty(this.data.status)) {
        filter.status = this.data.status;
      }
      if (!Util.isEmpty(this.data.menu_type)) {
        filter.menu_type = this.data.menu_type;
      }

      if (!Util.isEmpty(this.data.printer_type)) {
        filter.printer_type = this.data.printer_type;
      }

      let fields = this.data.fields;
      if (this.data.printer_type == 'stall') {
        delete fields['stall_id']
      }
      that.setData({
        fields: fields,
      })

      printerInitData(filter).then(res => {
        that.setData({...res.data})

        let fields = that.data.fields
        if (!Util.isEmpty(fields['stall_id']) && !Util.isEmpty(res.data.stalls)) {
          fields['stall_id'].options = res.data.stalls || []
        }
        if (!Util.isEmpty(res.data.printers)) {
          fields['printer_id'].options = res.data.printers || []
        }
        that.setData({
          fields: fields
        })
      })
    } else {
      return Util.Tips({title: "请先登录"}, {tab: 5, url: "../console/login"});
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  printerOrder(e) {
    const that = this, fields = that.data.fields;
    const formData = e.detail.value;

    if (!this.data.btnActive) {
      return Util.Tips({title: "正在提交打印，请不要重复提交"});
    }

    if ((Util.isEmpty(formData['printer_id']) && formData['printer_id'] != 0) || Util.isEmpty(fields['printer_id'].options[formData['printer_id']]))
      return Util.Tips({title: "请选择打印机", hideMask: true});

    formData['printer_id'] = fields['printer_id'].options[formData['printer_id']].id;
    formData['printer_type'] = this.data.printer_type;

    if (!Util.isEmpty(this.data.id)) {
      formData.ids = this.data.id;
    }
    if (!Util.isEmpty(this.data.current_date)) {
      formData.current_date = this.data.current_date;
    }
    if (!Util.isEmpty(this.data.status)) {
      formData.status = this.data.status;
    }
    if (!Util.isEmpty(this.data.menu_type)) {
      formData.menu_type = this.data.menu_type;
    }

    that.setData({
      btnActive: false
    })
    wx.showLoading({title: "正在打印..."})
    shopPrinter(formData).then((res) => {
      // Util.Tips({title: res.msg || "打印成功", hideMask: true}, {tab: 5, url: "../console/index"});
      Util.Tips({title: "正在打印中"}, {tab: 3});
    }).catch(errmsg => {
      Util.Tips({title: errmsg, hideMask: true});
    }).finally(() => {
      wx.hideLoading();
      that.setData({
        btnActive: true
      })
    })
  },

  checkboxChange(e) {
    let fields = this.data.fields;
    const values = e.detail.value, index = e.target.id;

    fields[index]['options'].map((option, ok) => {
      option.checked = false;
      values.map((v, i) => {
        if (v == option.id) {
          option.checked = true;
        }
      })
    })

    this.setData({
      fields: fields
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  bindChange(e) {
    let fields = this.data.fields;
    if (!e.target.id) {
      return;
    }
    fields[e.target.id].default_val = e.detail.value;
    this.setData({
      fields: fields
    })
  },

  /**
   * 初始化高度
   * @Author   thomashtao               bosslen
   */
  initTop() {
    const that = this,
      follow_doing = this.data.follow_doing;

    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})
      that.onLoadTabbar();
    }).then(() => {
      wx.createSelectorQuery().select('.navbar')
        .boundingClientRect((rect) => {
          if (!rect) {
            return;
          }
          let marginTop = rect.height
          if (follow_doing) {
            marginTop += 3
          }

          that.setData({
            marginTop: marginTop,
            top: marginTop + 10
          })
        })
        .exec();

    })
  },


  onLoadTabbar: function () {//底部tabbar返回数据
    const that = this;
    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})

      wx.createSelectorQuery().in(that).select('.weui-footer')
        .boundingClientRect(function (rect) {
          if (!rect) return;

          let bottom = parseInt(rect.height);
          if (that.data.isIphoneX) {
            bottom += 24;
          } else {
            bottom += 15;
          }
          that.setData({
            bottom: bottom
          })
        }).exec()
    });
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})